//
//  ZCStatusListViewModel.swift
//  weibo
//
//  Created by Ning Xie on 16/8/12.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class ZCStatusListViewModel: NSObject {

    lazy var statusList:[ZCStatusViewModel] = [ZCStatusViewModel]()
    
    
    
    func loadData(isPullup:Bool, callBack:(newInfo:String,isSuccess:Bool)->()){
        
        var sinceId: Int64 = 0
        var maxId: Int64 = 0
        
        //通过判断是否为上拉加载来修改向服务器发送的参数
        if isPullup {
            maxId = statusList.last?.status?.id ?? 0
            if maxId > 0 {
                maxId -= 1
            }
        }else{
            sinceId = statusList.first?.status?.id ?? 0
        }
        
        var newInfo:String = "暂无新微博"
        ZCNetworkTools.sharedNetworkTools.requestStatuses(ZCUserInfoViewModel.sharedUserInfo.accessToken!,since_id:sinceId,max_id:maxId) { (response, error) in
            
            //排除错误信息
            if error != nil{
                print("网络请求异常")
                
            }
            guard let dic = response as? [String:AnyObject] else{
                print("不是一个合法的字典")
                return
            }
            guard let dicArray = dic["statuses"] as? [[String :AnyObject]] else{
                print("字典格式不正确")
                return
            }
            //程序执行到此没有问题
            var tempArray = [ZCStatusViewModel]()
            
            for value in dicArray
            {
                let status = ZCStatusModel(dic: value)
                
                let statusViewModel = ZCStatusViewModel(status: status)
                tempArray.append(statusViewModel)
            }
            
            //通过判断是否为上拉加载加载数据
            if isPullup{
                self.statusList.appendContentsOf(tempArray)
            }else{
                self.statusList.insertContentsOf(tempArray, at: 0)
                
                if tempArray.count > 0{
                    
                    newInfo = "\(tempArray.count)条新微博"
                }
                
            }
            
            //回调闭包,返回成功的消息
            callBack(newInfo: newInfo,isSuccess: true)
        }
        
    }

    
}
